package bp.difference.context;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * RequestResponse过滤器
 * 预防HTTP响应头注入攻击
 */
@Component
public class RequestResponseFilter extends OncePerRequestFilter {


	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		SafeHttpServletResponse safeResponse = new SafeHttpServletResponse(response);

		// 设置安全相关的默认响应头
		setSecurityHeaders(safeResponse);

		filterChain.doFilter(request, safeResponse);
	}

	private void setSecurityHeaders(HttpServletResponse response) {
		// 防止点击劫持
		response.setHeader("X-Frame-Options", "DENY");

		// 防止MIME类型嗅探
		response.setHeader("X-Content-Type-Options", "nosniff");

		// XSS保护
		response.setHeader("X-XSS-Protection", "1; mode=block");

		// 内容安全策略
		response.setHeader("Content-Security-Policy",
				"default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'");

		// 禁止缓存敏感页面
		if (isSensitivePage()) {
			response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Expires", "0");
		}
	}

	private boolean isSensitivePage() {
		// 根据业务逻辑判断是否为敏感页面
		return true; // 根据实际情况调整
	}
}
